<template>
  <el-dialog v-loading="loading" :append-to-body="true" :close-on-click-modal="false" :visible.sync="visable" :title="isReApply?'重新提交学习交流申请':(isAdd ? '新增学习交流申请' : '修改学习交流申请')" width="820px" top="3vh" @close="closeDlg">
    <el-form ref="xform" v-enter2tab="true" :model="form" :rules="rules" size="small" label-width="120px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="申请标题" prop="applyName">
            <el-input v-model="form.applyName" maxlength="250" autocomplete="off" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="学习交流名称" prop="name">
            <el-input v-model="form.name" maxlength="250" autocomplete="off" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="组织单位" prop="organization">
            <el-input v-model="form.organization" maxlength="250" autocomplete="off" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="授课教师" prop="teacher">
            <el-input v-model="form.teacher" maxlength="100" autocomplete="off" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker v-model="form.startTime" type="date" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker v-model="form.endTime" type="date" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="学习课时" prop="period">
            <el-input v-model="form.period" maxlength="8" autocomplete="off" style="width:100px;" /><span>（节、小时）</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="学习内容" prop="content">
            <el-input v-model="form.content" type="textarea" maxlength="500" autocomplete="off" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="培训地址" prop="address">
            <el-input v-model="form.address" maxlength="250" autocomplete="off" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学习成果、成绩" prop="grade">
            <el-input v-model="form.grade" maxlength="200" autocomplete="off" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="附件" prop="appendFiles">
            <el-upload
              :headers="headers"
              :before-upload="beforeUploadAppend"
              :on-error="handleUploadError"
              :on-success="handleUploadSuccess"
              :on-exceed="handleUploadExceed"
              :on-remove="handleUploadRemove"
              :before-remove="beforeRemove"
              action="/upload/saveAppendFile"
              :file-list="appendFileList"
              :limit="10"
            >
              <el-button size="small" type="info">点击上传</el-button><span>(请上传相关文件，文件大小10M以内)</span>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <div v-if="isReApply" class="apply-comment-box">
          <div>
            <el-button plain @click="showComment()">审批意见...<i :class="['el-icon--right',commentShowed?'el-icon-arrow-down':'el-icon-arrow-right' ]" /></el-button>
          </div>
          <el-collapse-transition>
            <div v-show="commentShowed" class="apply-comment-content">
              <table class="billinfo-table" width="100%">
                <tr class="approve-tr">
                  <td colspan="2"><div class="bill-item"><label>审批意见</label><p>{{ form.approveComment }}</p></div></td>
                </tr>
                <tr>
                  <td><div class="bill-item"><label>审批人</label><p>{{ form.approveName }}</p></div></td>
                  <td><div class="bill-item"><label>审批时间</label><p>{{ form.approveTime | parseTime("{y}-{m}-{d}") }}</p></div></td>
                </tr>
              </table>
            </div>
          </el-collapse-transition>
        </div>
      </el-row>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import request from '@/utils/request'
import { getToken } from '@/utils/auth'
import { positiveInt } from '@/utils/validator.js'
export default {
  name: 'TrainingForm',
  data() {
    return {
      isReApply: false,
      isAdd: false,
      loading: false,
      visable: false,
      commentShowed: false,
      headers: {
        'Authorization': 'Bearer ' + getToken()
      },
      appendFileList: [],
      form: this.initForm(),
      rules: {
        applyName: [
          { required: true, message: '必填', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '必填', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '必填', trigger: 'blur' }
        ],
        organization: [
          { required: true, message: '必填', trigger: 'blur' }
        ],
        startTime: [
          { required: true, message: '必填', trigger: 'blur' }
        ],
        endTime: [
          { required: true, message: '必填', trigger: 'blur' }
        ],
        period: [
          { validator: positiveInt, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
  },
  methods: {
    initForm() {
      return {
        id: null,
        applyName: '',
        name: '',
        organization: '',
        teacher: '',
        startTime: '',
        endTime: '',
        period: '',
        content: '',
        address: '',
        grade: '',
        appendFiles: ''
      }
    },
    resetFields() {
      this.$refs['xform'].resetFields()
      this.form = this.initForm()
    },
    cancel() {
      this.closeDlg()
    },
    showComment() {
      this.commentShowed = !this.commentShowed
    },
    doSubmit() {
      this.$refs['xform'].validate((valid) => {
        if (valid) {
          this.loading = true
          if (this.appendFileList && this.appendFileList.length > 0) {
            this.form.appendFiles = JSON.stringify(this.appendFileList)
          } else {
            this.form.appendFiles = null
          }
          if (this.isReApply) {
            this.doRepply()
          } else {
            if (this.isAdd) {
              this.doAdd()
            } else this.doEdit()
          }
        }
      })
    },
    add() {
      this.isAdd = true
      this.visable = true
    },
    reApply(id) {
      this.isReApply = true
      this.edit(id)
    },
    edit(id) {
      request({ url: '/edu/training/' + id, method: 'get' }).then(data => {
        this.form = data
        // appenfile
        try {
          if (this.form.appendFiles) {
            this.appendFileList = JSON.parse(this.form.appendFiles)
          }
        } catch (e) { console.log(e) }
        this.isAdd = false
        this.visable = true
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    doRepply() {
      request({ url: '/edu/training/reApply', method: 'post', data: this.form }).then(res => {
        this.closeDlg()
        this.$notify({
          title: '重新提交成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.$parent.getList() // refrsh
      }).catch(err => {
        this.loading = false
        this.$message.error('重新提交错误！' + err.message)
      })
    },
    doAdd() {
      request({ url: '/edu/training/apply', method: 'post', data: this.form }).then(res => {
        this.closeDlg()
        this.$notify({
          title: '添加成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.$parent.getList() // refrsh
      }).catch(err => {
        this.loading = false
        this.$message.error('新增错误！' + err.message)
      })
    },
    doEdit() {
      request({ url: '/edu/training', method: 'put', data: this.form }).then(res => {
        this.closeDlg()
        this.$notify({
          title: '修改成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.$parent.getList()
      }).catch(err => {
        this.loading = false
        this.$message.error('修改错误！' + err.message)
      })
    },
    // appendfiles
    beforeUploadAppend(file) {
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 10MB!')
      }
      return isLt2M
    },
    handleUploadError: function(e) {
      // console.log(e)
      this.$message.error('上传文件失败！' + e)
    },
    handleUploadSuccess: function(res, file, fileList) {
      const f = {}
      f.name = res.data.name
      f.url = res.data.url
      this.appendFileList.push(f)
    },
    handleUploadExceed() {
      this.$message.warning('最多上传10个文件。')
    },
    handleUploadRemove(file, fileList) {
      this.appendFileList = fileList
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除附件 ？`)
    },
    closeDlg() {
      this.appendFileList = []
      this.visable = false
      this.isReApply = false
      this.resetFields()
      this.commentShowed = false
    }
  }
}
</script>
